#!/usr/bin/perl

open binFile, "./IAP/IAP.bin";
binmode(binFile);

my $fwords;
my $rd_buf;
my $rd_bytes;
my $rd_hex;
my $rd_arr;

$fwords = 0;
do {
	$rd_size = read(binFile, $rd_buf, 4);
	$rd_hex = unpack("H*", $rd_buf);
	my ($b0, $b1, $b2, $b3) = ($rd_hex =~ m/([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/);
	push @rd_arr, "$b3$b2$b1$b0";
	if( $rd_size == 4) {
		$fwords = $fwords + 1;
	}
} while( $rd_size == 4 );


`rm -rf RomTop.v FpgaRom2Kx32.coe`;
`echo "module RomTop(" > RomTop.v`;
`echo "\tinput  wire          clk_a," >> RomTop.v`;
`echo "\tinput  wire          rom_a_cs_n," >> RomTop.v`;
`echo "\tinput  wire [10 : 0] rom_a_addr," >> RomTop.v`;
`echo "\toutput wire [31 : 0] rom_a_rdata" >> RomTop.v`;
`echo ");" >> RomTop.v`;

`echo "reg  [31 : 0] s1_rom_out;" >> RomTop.v`;
#`echo "reg  [31 : 0] s0_rom_out;" >> RomTop.v`;
`echo "wire [31 : 0] s0_rom_out;" >> RomTop.v`;
`echo "\n\n" >> RomTop.v`;
`echo "always @(posedge clk_a)" >> RomTop.v`;
`echo "\tif(!rom_a_cs_n)" >> RomTop.v`;
`echo "\t\ts1_rom_out <= s0_rom_out;" >> RomTop.v`;

`echo "\n\n" >> RomTop.v`;


`echo "assign s0_rom_out = " >> RomTop.v`;
for (my $i = 0; $i < 2048; $i = $i + 1) {
	if($i < $fwords) {
		`echo "\t((rom_a_addr == 11\'d$i) ? 32'h@rd_arr[$i] : 32'h0) |" >> RomTop.v`;
	}
}
`echo "\t32'h0;" >> RomTop.v`;

#`echo "always @(*) begin" >> RomTop.v`;
#`echo "\tcase(rom_a_addr)" >> RomTop.v`;
#for (my $i = 0; $i < 1024; $i = $i + 1) {
#	if($i < $fwords) {
#		`echo "\t\t10\'d$i: s0_rom_out <= 32'h@rd_arr[$i];" >> RomTop.v`;
#	}
#}
#`echo "\t\tdefault: s0_rom_out <= 32\'h0;" >> RomTop.v`;
#`echo "\tendcase" >> RomTop.v`;
#`echo "end" >> RomTop.v`;

`echo "assign rom_a_rdata = s1_rom_out;" >> RomTop.v`;
`echo "endmodule" >> RomTop.v`;


#Generate FPGA COE
`echo "memory_initialization_radix=16;" >> FpgaRom2Kx32.coe`;
`echo "memory_initialization_vector="  >> FpgaRom2Kx32.coe`;
for (my $i = 0; $i < 2047; $i = $i + 1) {
	if($i < $fwords) {
		`echo "@rd_arr[$i]," >> FpgaRom2Kx32.coe`;
	} else {
		`echo "00000000," >> FpgaRom2Kx32.coe`;
	}
}
`echo "00000000;" >> FpgaRom2Kx32.coe`;


